<form method="get" action="index.php" id="currentsearch">
<?php
	$val = '';
	if(!empty($_GET['q']))
		$val = ' value="'.str_replace('"','&quot;',stripslashes($_GET['q'])).'"';
	echo 'Recherche : <input type="text" name="q" maxlength="255"'.$val.'>';
?>
</form>
	
<?php
	if(!empty($_GET['q']))
	{
		echo '<div id="searchresults">';
		
		$q = $_GET['q'];
		
		// POSTS
		$sql = "SELECT titre, id, date, MATCH (titre, texte) AGAINST ('*".$q."*' IN BOOLEAN MODE) AS cpt FROM posts WHERE MATCH (titre, texte) AGAINST ('*".$q."*' IN BOOLEAN MODE) ORDER BY cpt DESC, date DESC";
		$result = mysql_query($sql) or die(mysql_error());
		$nb1 = mysql_numrows($result);
		$s = ""; if($nb1>1) $s = "s";
		if($nb1>0)
		{
			echo "<h3>".$nb1." post".$s."</h3>";
			echo "<ul>";
			while($row = mysql_fetch_array($result)) 
			{
				$id = $row['id'];
				$titre = $row['titre'];
				/*
				$x = strpos($row['texte'],$q);
				$content = substr($row['texte'],$x-20,40);
				foreach(explode(' ',$q) as $term)
					$content = str_replace($term,"<strong>$term</strong>",$content);
				*/
				echo '<li><a href="./?p='.$id.'">'.$titre.'</a></li>';
			}
			echo "</ul>";
		}
		
		// COMMENTAIRES
		$sql = "SELECT id, ref, nom, MATCH (texte) AGAINST ('*".$q."*' IN BOOLEAN MODE) AS cpt FROM comments WHERE MATCH (texte) AGAINST ('*".$q."*' IN BOOLEAN MODE) ORDER BY cpt DESC";
		$result = mysql_query($sql) or die(mysql_error());
		$nb2 = mysql_numrows($result);
		$s =""; if($nb2>1) $s = "s";
		if($nb2>0)
		{
			echo "<h3>".$nb2." commentaire".$s."</h3>";
			echo "<ul>";
			while($row = mysql_fetch_array($result)) 
			{
				$id = $row['id'];
				$ref = $row['ref'];
				$nom = $row['nom'];
				$sql2 = "SELECT titre FROM posts WHERE id=".$ref;
				$result2 = mysql_query($sql2) or die(mysql_error());
				$row2 = mysql_fetch_array($result2);
				$titre = $row2['titre'];
				echo '<li>'.$nom.' sur <a href="./?p='.$ref.'#'.$id.'">'.$titre.'</a></li>';
			}
			echo "</ul>";
		}
		
		// COMMENTAIRES DE
		$sql = "SELECT id, ref, nom, MATCH (nom) AGAINST ('".$q."' IN BOOLEAN MODE) AS cpt FROM comments WHERE MATCH (nom) AGAINST ('".$q."' IN BOOLEAN MODE) ORDER BY cpt DESC";
		$result = mysql_query($sql) or die(mysql_error());
		$nb3 = mysql_numrows($result);
		$s =""; if($nb3>1) $s = "s";
		if($nb3>0)
		{
			echo "<h3>".$nb3." commentaire".$s." de ".$q."</h3>";
			echo "<ul>";
			while($row = mysql_fetch_array($result)) 
			{
				$id = $row['id'];
				$ref = $row['ref'];
				$sql2 = "SELECT titre FROM posts WHERE id=".$ref;
				$result2 = mysql_query($sql2) or die(mysql_error());
				$row2 = mysql_fetch_array($result2);
				$titre = $row2['titre'];
				echo '<li><a href="./?p='.$ref.'#'.$id.'">'.$titre.'</a></li>';
			}
			echo "</ul>";
		}
		
		// AUCUN RESULTAT
		if($nb1==0 && $nb2==0 && $nb3==0)
		{
			if(strlen($q)<=3)
				echo "<p>Le mot recherché doit avoir au minimum 4 lettres</p>";
			else
				echo "<p>Aucun résultat trouvé</p>";
		}
		
		echo "</div>";
	}
?>
